using System.Collections.Generic;
using Wintellect.PowerCollections;

namespace Quiki.Querying
{
    public class AndQuerySpecification : IQuerySpecification
    {
        public AndQuerySpecification()
        {
        }

        public AndQuerySpecification(IEnumerable<IQuerySpecification> components)
        {
            this.components.AddRange(components);
        }

        public IList<IQuerySpecification> Components
        {
            get { return components; }
        }

        public void AddComponentSpec (IQuerySpecification specification)
        {
            components.Add(specification);
        }

        public IEnumerable<WikiDocument> Filter(IEnumerable<WikiDocument> documents)
        {
            Set<WikiDocument> results = new Set<WikiDocument>();

            for (int i = 0; i < components.Count; i++)
            {
                IQuerySpecification component = components[i];
                IEnumerable<WikiDocument> filteredDocuments = component.Filter(documents);

                if (i == 0)
                    results.AddMany(filteredDocuments);
                else
                {
                    Set<WikiDocument> subset = new Set<WikiDocument>(filteredDocuments);
                    results = results.Intersection(subset);
                }
            }

            return results;
        }

        private List<IQuerySpecification> components = new List<IQuerySpecification>();
    }
}